/*
   Copyright 2011 marcopar@gmail.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
package eu.flatworld.cstrader;

import eu.flatworld.commons.Storage;
import eu.flatworld.commons.log.LogX;
import eu.flatworld.cstrader.data.ItemLine;
import eu.flatworld.cstrader.data.Pricelist;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import javax.swing.JOptionPane;
import javax.swing.RowFilter;
import javax.swing.RowSorter;
import javax.swing.table.TableRowSorter;

public class PricelistPanel extends javax.swing.JPanel {

    public final static String P_PRICELISTUPDATED = "pricelistpanel.pricelistupdated";
    Pricelist pricelist;
    Map<String, LocationProperty> locationsProperties;
    Map<String, ItemProperty> itemsProperties;
    Map<String, Long> weightCache;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");

    /** Creates new form PricelistPanel */
    public PricelistPanel() {
        initComponents();
    }

    public void setup(Pricelist pricelist) {
        locationsProperties = (Map<String, LocationProperty>) Storage.getStorage().get(Main.STORAGE_LOCATIONSPROPERTIES);
        itemsProperties = (Map<String, ItemProperty>) Storage.getStorage().get(Main.STORAGE_ITEMPROPERTIES);
        weightCache = (Map<String, Long>) Storage.getStorage().get(Main.STORAGE_WEIGHTCACHE);

        this.pricelist = pricelist;
        this.locationsProperties = locationsProperties;
        this.itemsProperties = itemsProperties;
        this.weightCache = weightCache;
        ItemsTableModel model = new ItemsTableModel(pricelist.getForSale(), true);
        for (int i = 0; i < model.getColumnCount(); i++) {
            jtForSale.setDefaultRenderer(model.getColumnClass(i), new ItemCellRenderer(locationsProperties, itemsProperties));

        }
        List<? extends RowSorter.SortKey> sk = jtForSale.getRowSorter().getSortKeys();
        jtForSale.setModel(model);
        //Tables.adjustColumnsWidth(jtForSale);
        jtForSale.getRowSorter().setSortKeys(sk);
        model = new ItemsTableModel(pricelist.getWanted(), false);
        for (int i = 0; i < model.getColumnCount(); i++) {
            jtWanted.setDefaultRenderer(model.getColumnClass(i), new ItemCellRenderer(locationsProperties, itemsProperties));
        }
        sk = jtWanted.getRowSorter().getSortKeys();
        jtWanted.setModel(model);
        //Tables.adjustColumnsWidth(jtWanted);
        jtWanted.getRowSorter().setSortKeys(sk);
        if (pricelist.getPricelistDate() != null) {
            jlLastUpdate.setText("Last update: " + sdf.format(pricelist.getPricelistDate()));
        } else {
            jlLastUpdate.setText(" ");
        }

        //forceTablesUpdate();
        //Tables.adjustColumnsWidth(jtWanted);
        //Tables.adjustColumnsWidth(jtForSale);
    }

    public void setRowFilter(RowFilter forSaleFilter, RowFilter wantedFilter) {
        if (forSaleFilter == null) {
            ((TableRowSorter) jtForSale.getRowSorter()).setRowFilter(null);
        } else {
            ((TableRowSorter) jtForSale.getRowSorter()).setRowFilter(forSaleFilter);
        }
        if (wantedFilter == null) {
            ((TableRowSorter) jtWanted.getRowSorter()).setRowFilter(null);
        } else {
            ((TableRowSorter) jtWanted.getRowSorter()).setRowFilter(wantedFilter);
        }
    }

    public void forceTablesUpdate() {
        ((ItemsTableModel) jtForSale.getModel()).fireTableDataChanged();
        ((ItemsTableModel) jtWanted.getModel()).fireTableDataChanged();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpmWanted = new javax.swing.JPopupMenu();
        jmiWantedEditPriceWatch = new javax.swing.JMenuItem();
        jmicbWantedIgnore = new javax.swing.JCheckBoxMenuItem();
        jpmForSale = new javax.swing.JPopupMenu();
        jmiForSaleEditPriceWatch = new javax.swing.JMenuItem();
        jmicbForSaleIgnore = new javax.swing.JCheckBoxMenuItem();
        jPanel1 = new javax.swing.JPanel();
        jbUpdateList = new javax.swing.JButton();
        jlLastUpdate = new javax.swing.JLabel();
        jbClearList = new javax.swing.JButton();
        jbExportList = new javax.swing.JButton();
        jSplitPane1 = new javax.swing.JSplitPane();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtWanted = new javax.swing.JTable();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtForSale = new javax.swing.JTable();

        jpmWanted.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {

            public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
            }

            public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
            }

            public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
                jpmWantedPopupMenuWillBecomeVisible(evt);
            }
        });

        jmiWantedEditPriceWatch.setText("Edit price watch");
        jmiWantedEditPriceWatch.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmiWantedEditPriceWatchActionPerformed(evt);
            }
        });
        jpmWanted.add(jmiWantedEditPriceWatch);

        jmicbWantedIgnore.setText("Ignore location");
        jmicbWantedIgnore.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmicbWantedIgnoreActionPerformed(evt);
            }
        });
        jpmWanted.add(jmicbWantedIgnore);

        jpmForSale.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {

            public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
            }

            public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
            }

            public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
                jpmForSalePopupMenuWillBecomeVisible(evt);
            }
        });

        jmiForSaleEditPriceWatch.setText("Edit price watch");
        jmiForSaleEditPriceWatch.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmiForSaleEditPriceWatchActionPerformed(evt);
            }
        });
        jpmForSale.add(jmiForSaleEditPriceWatch);

        jmicbForSaleIgnore.setText("Ignore location");
        jmicbForSaleIgnore.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmicbForSaleIgnoreActionPerformed(evt);
            }
        });
        jpmForSale.add(jmicbForSaleIgnore);

        jbUpdateList.setText("Update pricelist");
        jbUpdateList.setMargin(new java.awt.Insets(0, 2, 0, 2));
        jbUpdateList.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbUpdateListActionPerformed(evt);
            }
        });

        jlLastUpdate.setText(" ");

        jbClearList.setText("Clear pricelist");
        jbClearList.setMargin(new java.awt.Insets(0, 2, 0, 2));
        jbClearList.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbClearListActionPerformed(evt);
            }
        });

        jbExportList.setText("Export pricelist");
        jbExportList.setMargin(new java.awt.Insets(0, 2, 0, 2));
        jbExportList.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbExportListActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(jPanel1Layout.createSequentialGroup().addComponent(jbUpdateList).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jlLastUpdate, javax.swing.GroupLayout.DEFAULT_SIZE, 64, Short.MAX_VALUE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jbExportList).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jbClearList)));
        jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(jbUpdateList).addComponent(jbClearList).addComponent(jlLastUpdate).addComponent(jbExportList)));

        jSplitPane1.setDividerSize(5);
        jSplitPane1.setResizeWeight(0.5);

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Wanted"));

        jtWanted.setAutoCreateRowSorter(true);
        jtWanted.setComponentPopupMenu(jpmWanted);
        jScrollPane2.setViewportView(jtWanted);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 198, Short.MAX_VALUE));
        jPanel2Layout.setVerticalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 287, Short.MAX_VALUE));

        jSplitPane1.setRightComponent(jPanel2);

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("For sale"));

        jtForSale.setAutoCreateRowSorter(true);
        jtForSale.setModel(new javax.swing.table.DefaultTableModel(
                new Object[][]{},
                new String[]{}));
        jtForSale.setComponentPopupMenu(jpmForSale);
        jScrollPane1.setViewportView(jtForSale);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
                jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 197, Short.MAX_VALUE));
        jPanel3Layout.setVerticalGroup(
                jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 288, Short.MAX_VALUE));

        jSplitPane1.setLeftComponent(jPanel3);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 424, Short.MAX_VALUE));
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 315, Short.MAX_VALUE)));
    }// </editor-fold>//GEN-END:initComponents

    private void jpmForSalePopupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_jpmForSalePopupMenuWillBecomeVisible
        ItemsTableModel model = (ItemsTableModel) jtForSale.getModel();
        int row = jtForSale.getSelectedRow();
        if (row != -1) {
            jtForSale.setRowSelectionInterval(row, row);
            ItemLine i = model.getItemAtRow(jtForSale.convertRowIndexToModel(row));
            LocationProperty lp = locationsProperties.get(i.getLocation().getName());
            if (lp == null || !lp.isIgnore()) {
                jmicbForSaleIgnore.setSelected(false);
            } else {
                jmicbForSaleIgnore.setSelected(true);
            }
            jmiForSaleEditPriceWatch.setEnabled(true);
            jmicbForSaleIgnore.setEnabled(true);
        } else {
            jmiForSaleEditPriceWatch.setEnabled(false);
            jmicbForSaleIgnore.setEnabled(false);
        }
    }//GEN-LAST:event_jpmForSalePopupMenuWillBecomeVisible

    private void jpmWantedPopupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_jpmWantedPopupMenuWillBecomeVisible
        ItemsTableModel model = (ItemsTableModel) jtWanted.getModel();
        int row = jtWanted.getSelectedRow();
        if (row != -1) {
            jtWanted.setRowSelectionInterval(row, row);
            ItemLine i = model.getItemAtRow(jtWanted.convertRowIndexToModel(row));
            LocationProperty lp = locationsProperties.get(i.getLocation().getName());
            if (lp == null || !lp.isIgnore()) {
                jmicbWantedIgnore.setSelected(false);
            } else {
                jmicbWantedIgnore.setSelected(true);
            }
            jmiWantedEditPriceWatch.setEnabled(true);
            jmicbWantedIgnore.setEnabled(true);
        } else {
            jmiWantedEditPriceWatch.setEnabled(false);
            jmicbWantedIgnore.setEnabled(false);
        }
    }//GEN-LAST:event_jpmWantedPopupMenuWillBecomeVisible

    private void jmiWantedEditPriceWatchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmiWantedEditPriceWatchActionPerformed
        ItemsTableModel model = (ItemsTableModel) jtWanted.getModel();
        int row = jtWanted.getSelectedRow();
        ItemLine i = model.getItemAtRow(jtWanted.convertRowIndexToModel(row));
        ItemProperty ip = itemsProperties.get(i.getItem().getName());
        if (ip == null) {
            ip = new ItemProperty();
            ip.setName(i.getItem().getName());
        }
        PriceWatchDialog pwd = new PriceWatchDialog(JOptionPane.getFrameForComponent(this), ip);
        pwd.setVisible(true);
        if (pwd.getItemPorperties() != null) {
            itemsProperties.put(ip.getName(), ip);
        }
        forceTablesUpdate();
    }//GEN-LAST:event_jmiWantedEditPriceWatchActionPerformed

    private void jmicbWantedIgnoreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmicbWantedIgnoreActionPerformed
        ItemsTableModel model = (ItemsTableModel) jtWanted.getModel();
        int row = jtWanted.getSelectedRow();
        ItemLine i = model.getItemAtRow(jtWanted.convertRowIndexToModel(row));
        LocationProperty ln = locationsProperties.get(i.getLocation().getName());
        if (ln == null) {
            ln = new LocationProperty();
            ln.setName(i.getLocation().getName());
            ln.setIgnore(false);
            locationsProperties.put(ln.getName(), ln);
        }
        ln.setIgnore(jmicbWantedIgnore.isSelected());
        firePropertyChange(P_PRICELISTUPDATED, null, pricelist);
    }//GEN-LAST:event_jmicbWantedIgnoreActionPerformed

    private void jmiForSaleEditPriceWatchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmiForSaleEditPriceWatchActionPerformed
        ItemsTableModel model = (ItemsTableModel) jtForSale.getModel();
        int row = jtForSale.getSelectedRow();
        ItemLine i = model.getItemAtRow(jtForSale.convertRowIndexToModel(row));
        ItemProperty ip = itemsProperties.get(i.getItem().getName());
        if (ip == null) {
            ip = new ItemProperty();
            ip.setName(i.getItem().getName());
        }
        PriceWatchDialog pwd = new PriceWatchDialog(JOptionPane.getFrameForComponent(this), ip);
        pwd.setVisible(true);
        if (pwd.getItemPorperties() != null) {
            itemsProperties.put(ip.getName(), ip);
        }
        forceTablesUpdate();
    }//GEN-LAST:event_jmiForSaleEditPriceWatchActionPerformed

    private void jmicbForSaleIgnoreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmicbForSaleIgnoreActionPerformed
        ItemsTableModel model = (ItemsTableModel) jtForSale.getModel();
        int row = jtForSale.getSelectedRow();
        ItemLine i = model.getItemAtRow(jtForSale.convertRowIndexToModel(row));
        LocationProperty ln = locationsProperties.get(i.getLocation().getName());
        if (ln == null) {
            ln = new LocationProperty();
            ln.setName(i.getLocation().getName());
            ln.setIgnore(false);
            locationsProperties.put(ln.getName(), ln);
        }
        ln.setIgnore(jmicbForSaleIgnore.isSelected());
        firePropertyChange(P_PRICELISTUPDATED, null, pricelist);
    }//GEN-LAST:event_jmicbForSaleIgnoreActionPerformed

    private void jbUpdateListActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbUpdateListActionPerformed
        ImportPricelistDialog ipd = new ImportPricelistDialog(JOptionPane.getFrameForComponent(this), pricelist.getSystem());
        ipd.setVisible(true);
        String text = ipd.getImportedText();
        if (text == null) {
            return;
        }
        Pricelist old = pricelist;
        try {
            if (text.toLowerCase().contains("<html>")) {
                pricelist = PricelistsTools.importPricelistFromSource(text, pricelist.getSystem());
            } else {
                pricelist = PricelistsTools.importPricelist(text, pricelist.getSystem());
            }
        } catch (Exception ex) {
            LogX.log(Level.SEVERE, "Error importing the pricelist.", ex, true);
            LogX.log(Level.SEVERE, "[[[ " + text + " ]]]");
            return;
        }

        firePropertyChange(P_PRICELISTUPDATED, old, pricelist);
    }//GEN-LAST:event_jbUpdateListActionPerformed

    private void jbClearListActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbClearListActionPerformed
        int resp = JOptionPane.showConfirmDialog(this, "Do you want to clear the pricelist?", "Exit", JOptionPane.YES_NO_OPTION);
        if (resp != JOptionPane.YES_OPTION) {
            return;
        }
        Pricelist old = pricelist;
        pricelist = new Pricelist();
        pricelist.setSystem(old.getSystem());
        firePropertyChange(P_PRICELISTUPDATED, old, pricelist);
    }//GEN-LAST:event_jbClearListActionPerformed

    private void jbExportListActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbExportListActionPerformed
        ExportPricelistDialog ipd = new ExportPricelistDialog(JOptionPane.getFrameForComponent(this), pricelist);
        ipd.setVisible(true);
    }//GEN-LAST:event_jbExportListActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JButton jbClearList;
    private javax.swing.JButton jbExportList;
    private javax.swing.JButton jbUpdateList;
    private javax.swing.JLabel jlLastUpdate;
    private javax.swing.JMenuItem jmiForSaleEditPriceWatch;
    private javax.swing.JMenuItem jmiWantedEditPriceWatch;
    private javax.swing.JCheckBoxMenuItem jmicbForSaleIgnore;
    private javax.swing.JCheckBoxMenuItem jmicbWantedIgnore;
    private javax.swing.JPopupMenu jpmForSale;
    private javax.swing.JPopupMenu jpmWanted;
    private javax.swing.JTable jtForSale;
    private javax.swing.JTable jtWanted;
    // End of variables declaration//GEN-END:variables
}
